package com.cloud.controller;

import com.cloud.Pay;
import com.cloud.R;
import com.cloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: my
 * @BelongsPackage: com.cloud.controller
 * @Author: ji ge
 * @CreateTime: 2024-02-02  19:09
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

//    @Resource
//    private DiscoveryClient discoveryClient;

    @GetMapping("/getPayment/{id}")
    public R<Pay> get(@PathVariable("id") Long id) {
        Pay pay = paymentService.get(id);
        return new R<Pay>(200, "select success server port:" + serverPort, pay);
    }

    @PostMapping("/payment/create")
    public R<Pay> create(@RequestBody Pay pay) {
        Pay insert = paymentService.insert(pay);
        return new R<Pay>(200, "select success server port:" + serverPort, insert);

    }

    @GetMapping("/payment/queryAllByLimit")
    public R<List<Pay>> queryAllByLimit(@RequestParam(defaultValue = "0") int offset,
                                        @RequestParam(defaultValue = "10") int limit) {
        List<Pay> payList = paymentService.queryAllByLimit(offset, limit);
        return new R(200, "select success ,server port :" + serverPort, payList);
    }

//    @GetMapping("/discovery")
//    public Object discovery() {
//        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
//        instances.forEach(i -> {
//            System.out.println(i.getServiceId() + "\t" + i.getHost() + "\t" + i.getPort() + "\t" + i.getUri());
//        });
//        return this.discoveryClient;
//    }

    @GetMapping("/payment/lb")
    public String lb() {
        return serverPort;
    }

    @GetMapping("/payment/feignTimeOut")
    public String feignTimeOut() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/payment/paymentZipkin")
    public String paymentZipkin() {
        return "payment zipkin fall back";
    }
}
